package Component;

import org.json.JSONException;
import org.json.JSONObject;

import com.badlogic.gdx.graphics.g2d.SpriteBatch;

import Clock.Clock;
import GameObj.GameObject;
import Res.Resource;
import Scene.Renderable;
import com.badlogic.gdx.math.Matrix4;
import com.badlogic.gdx.math.Rectangle;
public class GraphComponent extends GameComponent implements Renderable
{
	public boolean bVis_ = true;
	public Resource res = null;
	public Rectangle boundingbox = new Rectangle();
	public void Render(SpriteBatch spriteBatch,Matrix4 matrix)
	{
		GameObject GO = GetHost();
		if (res != null && GO != null)
		{
			Matrix4 matrixOut = matrix.cpy();
			matrixOut.translate(x, y, 0);
			res.Render(spriteBatch, matrixOut);			
		}
	}
	
	public int GetTypeId()
	{
		return E_GRAPHCOMPONENT;
	}
	
	public void SetVisible(boolean bVis)
	{
		bVis_ = bVis;
	}
	
	public boolean Load(JSONObject jsonComp)
	{
		super.Load(jsonComp);
		boolean bResult = false;
		try
		{	 
			// loading resource
			x = (float)jsonComp.getDouble("x");
			y = (float)jsonComp.getDouble("y");
			int nType = jsonComp.getInt("restype");
			res = Resource.createResourceByType(nType);
			if (res != null)
			{
				if (jsonComp.has("resfile"))
				{
					String fileName = jsonComp.getString("resfile");
					res.LoadRes(fileName);	
					bResult = true;

				}
				else
				{
					res.LoadRes(jsonComp);	
					bResult = true;
				}
			}
		}
		catch(JSONException e)
		{
			
		}
		
		if (res != null)
		{
			Rectangle rt = new Rectangle();
			rt.x = -res.nWidth / 2;
			rt.y = -res.nHeight / 2;
			
			rt.width = res.nWidth;
			rt.height = res.nHeight;	
			
			SetBoundingBox(rt);			
		}
		
		return bResult;		
	}
	
	public void Update(Clock clock)
	{
		if (!enable)
		{
			return;
		}
		
		if (res != null)
		{
			res.Update(clock);	
		
		}
	}
	
	
	
	public Rectangle GetBoundingBox()
	{
		return boundingbox;
	}
	
	public void SetBoundingBox(Rectangle rt)
	{
		boundingbox = rt;
	}
}
